<?php
/**
 * Created by PhpStorm.
 * User: qingyun
 * Date: 18/7/27
 * Time: 下午6:36
 */

namespace app\api\controller;

use app\common\controller\Base;
use app\common\controller\Token;
use think\Db;
use think\Request;

//人员管理
class Admin extends Base
{
    //展示或搜索人员管理列表
    public function index(){
        if (Request::instance()->isGet()){
            $key = Request::instance()->param('key',null);  //获取搜索类型：1账号，2姓名
            $keywords = Request::instance()->param('keywords',null);    //获取搜索关键词
            $page = Request::instance()->param('page',null);    //获取页码
            $page = empty($page) ? 1 : $page;
            $where = '1 = 1 ';
            //搜索关键词不为空的情况下进行模糊查询
            if ($keywords != null) {
                if($key == 1) {
                    $where .= "and a.account like '%$keywords%'";
                }elseif ($key == 2) {
                    $where .= "and a.name like '%$keywords%'";
                }
                $list = Db::name('admin')->alias('a')->join('roles r','a.roles_id = r.id','LEFT')->where($where)->order('a.addTime', 'desc')->field('a.id,a.account,a.name,a.addTime,r.title')->select();
                if(empty($list)){
                    $this->responseJson([],1106);
                }
            }else {
                //搜索关键词为空的情况下按照添加时间倒序排列进行查询
                $list = Db::name('admin')->alias('a')->join('roles r','a.roles_id = r.id','LEFT')->order('a.addTime', 'desc')->field('a.id,a.account,a.name,a.addTime,r.title')->select();
            }
            $data = paging($list,$page);
            $this->responseJson($data,0);
        }
        $this->responseJson([],1000);
    }

    //添加人员
    public function addSave(){
        if (Request::instance()->isPost()){
            $account = Request::instance()->param('account',null);//获取账号，必填
            if (empty($account)){
                $this->responseJson([],1107);
            }
            //判断此账号是否已存在
            $id = Db::name('admin')->where('account',$account)->field('id')->find();
            if (!empty($id['id'])){
                $this->responseJson([],1113);
            }
            $name = Request::instance()->param('name',null);//获取姓名，必填
            if (empty($name)){
                $this->responseJson([],1108);
            }
            $password = Request::instance()->param('password',null);//获取密码，必填
            if (empty($password)){
                $this->responseJson([],1109);
            }
            $pwd = Request::instance()->param('pwd',null);//获取确认密码，必填
            if (empty($pwd)){
                $this->responseJson([],1110);
            }
            //判断两次输入的密码是否一致
            if ($password != $pwd){
                $this->responseJson([],1115);
            }
            $roles_id = Request::instance()->param('roles_id',null);//获取用户角色，必填
            if (empty($roles_id)){
                $this->responseJson([],1111);
            }
            $salt = salt();
            $password = md5($password);
            $password = md5($password . $salt . '$%$^%$&^%&');//密码加密并加盐
            $arr = [
                'name' => $name,
                'account' => $account,
                'password' => $password,
                'salt'     => $salt,
                'roles_id' => $roles_id,
                'addTime'  => time()
            ];
            Db::startTrans();//开启事务
            $data = Db::name('admin')->insert($arr);//添加数据
            if(!$data){
                $this->responseJson([],1002);
            }
            //角色数量加一
            $user_num = Db::name('roles')->where('id',$roles_id)->setInc('user_num');
            if (empty($user_num)){
                Db::rollback();//如果角色数量加一失败，回滚事务
                $this->responseJson([],1005);
            }
            Db::commit();//提交事务
            $this->responseJson([],0);
        }
        $this->responseJson([],1000);
    }

    //编辑人员
    public function edit(){
        if (Request::instance()->isPost()){
            $id = Request::instance()->param('id',null);//获取人员ID，必传
            if (empty($id)){
                $this->responseJson([],1116);
            }
            $account = Request::instance()->param('account',null);//获取账号，必填
            if (empty($account)){
                $this->responseJson([],1107);
            }
            //判断账号是否已存在
            $account_num = Db::name('admin')->where('account',$account)->count();
            if ($account_num > 1){
                $this->responseJson([],1132);
            }
            if ($account_num == 1){
                $ids = Db::name('admin')->where('account',$account)->field('id')->find();
                if ($ids['id'] != $id) {
                    $this->responseJson([], 1131);
                }
            }
            $name = Request::instance()->param('name',null);//获取姓名，必填
            if (empty($name)){
                $this->responseJson([],1108);
            }
            $roles_id = Request::instance()->param('roles_id',null);//获取用户角色，必填
            if (empty($roles_id)){
                $this->responseJson([],1111);
            }
            $arr = [
                'name' => $name,
                'account' => $account,
                'roles_id' => $roles_id,
            ];
            Db::startTrans();//开启事务
            $data = Db::name('admin')->where('id',$id)->update($arr);//更新数据
            if($data === false){
                $this->responseJson([],1005);
            }
            //查询以前的角色ID
            $role_id = Db::name('admin')->where('id',$id)->field('roles_id')->find();
            if (empty($role_id['roles_id'])){
                $this->responseJson([],1004);
            }
            //如果以前跟现在的用户角色不一样，以前的用户角色数量-1，现在的用户角色数量+1
            if ($role_id['roles_id'] != $roles_id){
                //以前的角色数量-1
                $users_num = Db::name('roles')->where('id',$role_id)->setDec('user_num');
                //现在的角色数量+1
                $user_num = Db::name('roles')->where('id',$roles_id)->setInc('user_num');
                if (empty($user_num) || empty($users_num)){
                    Db::rollback();//角色数量更新失败就回滚事务
                    $this->responseJson([],1002);
                }
            }
            Db::commit();//提交事务
            $this->responseJson([],0);
        }
        $this->responseJson([],1000);
    }

    //人员详情
    public function adminDetails(){
        if (Request::instance()->isGet()){
            $id = Request::instance()->param('id',null);    //人员ID;
            if (empty($id)){    //人员ID不能为空
                $this->responseJson([],1116);
            }
            $admin = Db::name('admin')->alias('a')->join('roles r','r.id = a.roles_id','LEFT')->where('a.id',$id)->field('a.name,a.account,a.roles_id,r.title')->find();
            if (empty($admin)){
                $this->responseJson([],1004);
            }
            $this->responseJson($admin,0);
        }
        $this->responseJson([],1000);
    }

    //删除人员
    public function delete(){
        if (Request::instance()->isDelete()){
            $id = Request::instance()->param('id',null);//获取人员ID，必传
            if (empty($id)){
                $this->responseJson([],1116);
            }
            $roles_id = Db::name('admin')->where('id',$id)->field('roles_id')->find();
            if (empty($roles_id)){
                $this->responseJson([],1004);
            }
            Db::startTrans();//开启事务
            $del = Db::name('admin')->where('id',$id)->delete();//删除人员
            if (empty($del)){
                $this->responseJson([],1003);
            }
            //被删除人员的角色用户数量—1
            $user_num = Db::name('roles')->where('id',$roles_id['roles_id'])->setDec('user_num');
            if (empty($user_num)){
                Db::rollback();//角色数量更新失败就回滚事务
                $this->responseJson([],1005);
            }
            Db::commit();//提交事务
            $this->responseJson([],0);
        }
        $this->responseJson([],1000);
    }

    //重置密码
    public function reset(){
        if(Request::instance()->isPost()){
            $id = Request::instance()->param('id',null);//获取重置密码用户的ID，必传
            if(empty($id)){
                $this->responseJson([],1116);
            }
            $tmp = Db::name('admin')->where(['id'=>$id])->field('salt')->find();//获取用户的盐
            if(empty($tmp['salt'])){
                $this->responseJson([],1004);
            }
            $passWord = md5(123456);    //后台重置密码默认为 123456
            $passWord = md5($passWord . $tmp['salt'] . '$%$^%$&^%&');//密码加密并加盐
            //更新密码
            $data = Db::name('admin')->where(['id'=>$id])->update(['password'=>$passWord,'addTime'=>time()]);
            if(empty($data)){
                $this->responseJson([],1117);
            }
            $this->responseJson($data,0);
        }
        $this->responseJson([],1000);
    }

    //修改密码
    public function modifyPass(){
        if (Request::instance()->isPost()){
            $token = Request::instance()->param('token',null);
            if (empty($token)){
                $this->responseJson([],1124);
            }
            $oldPwd = Request::instance()->param('oldPwd',null);//获取旧密码
            $password = Request::instance()->param('password',null);//获取新密码
            $confirmPwd = Request::instance()->param('confirmPwd',null);//获取确认密码
            if (empty($oldPwd) || empty($password) || empty($confirmPwd)){
                $this->responseJson([],1123);
            }
            //查询用户信息
            $admin = Db::name('admin')->where('token',$token)->find();
            if (empty($admin)){
                $this->responseJson([],1004);
            }
            //判断旧密码是否正确
            if ($admin['password'] != md5(md5($oldPwd).$admin['salt'].'$%$^%$&^%&')){
                $this->responseJson([],1125);
            }
            //判断旧密码与新密码是否一致
            if ($password == $oldPwd){
                $this->responseJson([],1126);
            }
            //判断确认密码与新密码是否一致
            if ($password != $confirmPwd){
                $this->responseJson([],1115);
            }
            //更新密码
            $upData = Db::name('admin')->where(['token' => $token])->update(['password' => md5(md5($password).$admin['salt'].'$%$^%$&^%&')]);
            if(empty($upData)){
                $this->responseJson([] ,1005);
            }
            //更新Token
            $tmp = new Token();
            $setToken = $tmp->setToken($admin['account']);
            $this->responseJson([],1127);
        }
        $this->responseJson([],1000);
    }

    //用户角色下拉列表
    public function roleList(){
        if (Request::instance()->isGet()){
            $role = Db::name('roles')->where('activity',1)->field('title,id')->select();
            $this->responseJson($role,0);
        }
        $this->responseJson([],1000);
    }
}